//
//  DateAlertView.m
//  Peso Guide
//
//  Created by macbook on 2025/6/13.
//

#import "DateAlertView.h"

@interface DateAlertView () <UIPickerViewDataSource, UIPickerViewDelegate>

@property (nonatomic, strong) UIView *grayView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIImageView *backImg;
@property (nonatomic, strong) UIButton *confirmButton;
@property (nonatomic, strong) UIButton *closeButton;
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) UIView *chooseDateView;
@property (nonatomic, strong) UIPickerView *pickerView;

// 数据源
@property (nonatomic, strong) NSMutableArray *days;
@property (nonatomic, strong) NSArray *months;
@property (nonatomic, strong) NSMutableArray *years;

// 当前选择
@property (nonatomic, assign) NSInteger selectedDay;
@property (nonatomic, assign) NSInteger selectedMonth;
@property (nonatomic, assign) NSInteger selectedYear;

// 当前日期
@property (nonatomic, strong) NSDate *currentDate;

@end

@implementation DateAlertView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // 获取当前日期
        _currentDate = [NSDate date];
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:_currentDate];
        _selectedYear = components.year;
        _selectedMonth = components.month;
        _selectedDay = components.day;
        
        // 初始化UI
        _grayView = [PesoKit createViewWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight) backGroundColor:[UIColor colorWithHexString:@"#000000" alpha:0.7]];
        [self addSubview:_grayView];
        
        _backImg = [PesoKit createImageViewWithFrame:CGRectMake((KScreenWidth-301)/2.0, (KScreenHeight-411)/2.0-20, 301, 411) imageNamed:@"ic_identity_alert_back"];
        _backImg.userInteractionEnabled = YES;
        _backImg.clipsToBounds = YES;
        _backImg.layer.cornerRadius = 15.0f;
        [self addSubview:_backImg];
        
        _titleLabel = [PesoKit createLabelWithFrame:CGRectMake(0, 0, _backImg.width, 60) backGroundColor:[UIColor clearColor] text:[Lang set:@"Please select"] textColor:ColorHex(@"#000000") font:FONT(FontWeightStyleMedium, 20)];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        [_backImg addSubview:_titleLabel];
        
        _confirmButton = [PesoKit createButtonWithFrame:CGRectMake((_backImg.width-214)/2.0, _backImg.height-32-44, 214, 44) backGroundColor:ColorHex(@"#FE7133") title:[Lang set:@"Confirm"] titleColor:ColorHex(@"#FFFFFF") font:FONT(FontWeightStyleMedium, 18)];
        [_confirmButton addTarget:self action:@selector(confirmButtonClick) forControlEvents:UIControlEventTouchUpInside];
        _confirmButton.clipsToBounds = YES;
        _confirmButton.layer.cornerRadius = 22.0f;
        [_backImg addSubview:_confirmButton];
        
        _closeButton = [[UIButton alloc] initWithFrame:CGRectMake((KScreenWidth-26)/2.0, _backImg.bottom+16, 26, 26)];
        [_closeButton setBackgroundImage:[UIImage imageNamed:@"ic_identity_close"] forState:0];
        [_closeButton addTarget:self action:@selector(closeButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_closeButton];
        
        _chooseDateView = [PesoKit createViewWithFrame:CGRectMake(16, 60, 301-16*2, 335-40-16-16) backGroundColor:[UIColor clearColor]];
        [_backImg addSubview:_chooseDateView];
        
        // 初始化选择器
        [self setupPickerView];
    }
    return self;
}

- (void)setupPickerView {
    // 初始化数据源
    [self initDataSource];
    
    // 创建选择器
    _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, _chooseDateView.frame.size.width, _chooseDateView.frame.size.height)];
    _pickerView.dataSource = self;
    _pickerView.delegate = self;
    [_chooseDateView addSubview:_pickerView];
    
    // 设置默认选择（今天）
    [self setDefaultSelection];
}

- (void)initDataSource {
    // 初始化月份（英文）
    _months = @[[Lang set:@"January"], [Lang set:@"February"], [Lang set:@"March"], [Lang set:@"April"], [Lang set:@"May"], [Lang set:@"June"],
                [Lang set:@"July"], [Lang set:@"August"], [Lang set:@"September"], [Lang set:@"October"], [Lang set:@"November"], [Lang set:@"December"]];
    
    // 初始化年份（1900-当前年）
    _years = [NSMutableArray array];
    for (NSInteger year = 1900; year <= _selectedYear; year++) {
        [_years addObject:[NSString stringWithFormat:@"%ld", (long)year]];
    }
    
    // 初始化天数（根据当前年月）
    [self updateDaysForCurrentMonth];
}

- (void)updateDaysForCurrentMonth {
    _days = [NSMutableArray array];
    NSInteger daysInMonth = [self daysInMonth:_selectedMonth year:_selectedYear];
    
    // 如果是当前年月，天数不超过今天
    NSInteger maxDay = daysInMonth;
    if (_selectedYear == [self currentYear] && _selectedMonth == [self currentMonth]) {
        maxDay = [self currentDay];
    }
    
    for (NSInteger day = 1; day <= maxDay; day++) {
        [_days addObject:[NSString stringWithFormat:@"%ld", (long)day]];
    }
}

- (NSInteger)daysInMonth:(NSInteger)month year:(NSInteger)year {
    if (month == 4 || month == 6 || month == 9 || month == 11) {
        return 30;
    } else if (month == 2) {
        if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
            return 29;
        } else {
            return 28;
        }
    } else {
        return 31;
    }
}

- (void)setDefaultSelection {
    // 设置默认选择（今天）
    [_pickerView selectRow:(_selectedDay - 1) inComponent:2 animated:NO];
    [_pickerView selectRow:(_selectedMonth - 1) inComponent:1 animated:NO];
    [_pickerView selectRow:(_selectedYear - 1900) inComponent:0 animated:NO];
}

#pragma mark - UIPickerView DataSource & Delegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 3; // 日、月、年
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    switch (component) {
        case 0: return _years.count;       // 年
        case 1: return _months.count;     // 月
        case 2: return _days.count;      // 日
        default: return 0;
    }
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel *label = (UILabel *)view;
    if (!label) {
        label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:16];
    }
    
    // 设置文本
    switch (component) {
        case 0: label.text = _years[row]; break;
        case 1: label.text = _months[row]; break;
        case 2: label.text = _days[row]; break;
    }
    
    // 设置选中状态样式
    BOOL isSelected = [pickerView selectedRowInComponent:component] == row;
    label.font = isSelected ? [UIFont boldSystemFontOfSize:16] : [UIFont systemFontOfSize:16];
    label.textColor = isSelected ? ColorHex(@"#1A7A35") : ColorHex(@"#666666");
    
    return label;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    switch (component) {
        case 0: return 70;   // 年
        case 1: return 100;  // 月（英文较长）
        case 2: return 50;   // 日
        default: return 0;
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    // 更新选择的值
    switch (component) {
        case 2: // 日
            _selectedDay = [_days[row] integerValue];
            break;
        case 1: { // 月
            _selectedMonth = row + 1;
            [self updateDaysForCurrentMonth];
            
            // 检查日期是否有效
            if (_selectedDay > _days.count) {
                _selectedDay = _days.count;
                [pickerView selectRow:(_selectedDay - 1) inComponent:0 animated:YES];
            }
            [pickerView reloadComponent:0];
            break;
        }
        case 0: { // 年
            _selectedYear = [_years[row] integerValue];
            [self updateDaysForCurrentMonth];
            
            // 检查日期是否有效
            if (_selectedDay > _days.count) {
                _selectedDay = _days.count;
                [pickerView selectRow:(_selectedDay - 1) inComponent:0 animated:YES];
            }
            [pickerView reloadComponent:0];
            break;
        }
    }
    
    // 刷新所有组件以更新样式
    [pickerView reloadAllComponents];
}

#pragma mark - Helper methods
- (NSInteger)currentYear {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    return [calendar component:NSCalendarUnitYear fromDate:_currentDate];
}

- (NSInteger)currentMonth {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    return [calendar component:NSCalendarUnitMonth fromDate:_currentDate];
}

- (NSInteger)currentDay {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    return [calendar component:NSCalendarUnitDay fromDate:_currentDate];
}

#pragma mark - Button Actions
- (void)confirmButtonClick {
    // 打印格式: 年/月/日 (1995/10/15)
    NSString *dateStr = [NSString stringWithFormat:@"%02ld-%02ld-%ld",
                         (long)_selectedYear,
                         (long)_selectedMonth,
                         (long)_selectedDay];
    DLog(@"Selected date: %@", dateStr);
    
    if (self.selectionHandler) {
        self.selectionHandler(@{@"date":dateStr});
    }
    
    [self removeFromSuperview];
}

- (void)closeButtonClick {
    [self removeFromSuperview];
}

@end
